package com.lyw.utils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {

  private final static String CLEARANCE_ROOM_POSITION_PATH = "C:\\Users\\Administrator\\Desktop\\TPlan\\TPlan\\src\\main\\resources\\config\\clearanceRoom.txt";

  private FileUtils() {}

  public static List<int[]> getClearanceRoomPosition() throws IOException {

    List<String> allLines = Files.readAllLines(Paths.get(CLEARANCE_ROOM_POSITION_PATH), StandardCharsets.UTF_8);
    if (allLines.size() == 0) {
      return new ArrayList<>();
    }
    String clearance_position_info = allLines.get(0);
    if (clearance_position_info.length() == 0) {
      return new ArrayList<>();
    }
    String[] all_positions = clearance_position_info.split(",");
    List<int[]> res = new ArrayList<>();
    for (String all_position : all_positions) {
      String[] split = all_position.split("-");
      res.add(new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1])});
    }

    return res;
  }

  public static void writeClearanceRoomPosition(int[] clear_position) throws Exception {
    List<int[]> clearanceRoomPosition = getClearanceRoomPosition();
    if (clearanceRoomPosition.size() == 0) {
      String s = clear_position[0] + "-" + clear_position[1];
      Files.write(Paths.get(CLEARANCE_ROOM_POSITION_PATH), s.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.APPEND);
      return;
    }
    int[] ints = clearanceRoomPosition.get(clearanceRoomPosition.size() - 1);
    if (ints[0] == clear_position[0] && ints[1] == clear_position[1]) {
      return;
    }
    long size = Files.size(Paths.get(CLEARANCE_ROOM_POSITION_PATH));
    String s = clear_position[0] + "-" + clear_position[1];
    if (size != 0) {
      s = "," + s;
    }
    Files.write(Paths.get(CLEARANCE_ROOM_POSITION_PATH), s.getBytes(), StandardOpenOption.WRITE, StandardOpenOption.APPEND);
  }

  public static void clearClearancePosition() throws IOException {
    Files.write(Paths.get(CLEARANCE_ROOM_POSITION_PATH), new byte[0]);
  }
}
